package xin.ganbo.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import xin.ganbo.entity.User;
import xin.ganbo.utils.AppUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * 系统响应时间日志监控拦截器
 * @author ganbo E-mail:bo.gan@56qq.com
 * @since 2017-12-04 11:16
 */

public class LongTimeLoggerInterceptor extends HandlerInterceptorAdapter {

    private static final String ATTR_CONTROLLER_EXECUTION_START_TIME = "ControllerExcutionStartTime";
    private static final int EXECUTION_TIME_FOR_LOGGING = 500;
    private final Logger logger = LoggerFactory.getLogger(LongTimeLoggerInterceptor.class);

    /**
     * 处理controller之前触发
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute(ATTR_CONTROLLER_EXECUTION_START_TIME, System.currentTimeMillis());
        return true;
    }

    /**
     * 返回处理(已经渲染了页面)
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String handleName;
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            handleName = handlerMethod.getShortLogMessage();
        } else {
            handleName = handler.getClass().getName();
        }

        long startTime = (long) request.getAttribute(ATTR_CONTROLLER_EXECUTION_START_TIME);
        long costTime = System.currentTimeMillis() - startTime;
        if (costTime > EXECUTION_TIME_FOR_LOGGING) {
            StringBuffer logMsg = new StringBuffer();
            logMsg.append("Controller执行时间过长，耗时:").append(costTime).append("ms, ");
            logMsg.append("调用方法:").append(handleName).append("\n");
            User user = AppUtil.getSessionUserInformation(request.getSession());
            if (user != null) {
                logMsg.append("User Id:").append(user.getId()).append(", User name:").append(user.getUsername()).append("\n");
            }
            logMsg.append("URL:").append(request.getRequestURL()).append("\n");
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String header = headerNames.nextElement();
                logMsg.append("Header name:").append(header).append(", value:").append(request.getHeader(header)).append("\n");
            }
            Enumeration<String> params = request.getParameterNames();
            while (params.hasMoreElements()) {
                String param = params.nextElement();
                logMsg.append("Param name:").append(param).append(", value:").append(request.getParameter(param)).append("\n");
            }
            logger.warn(logMsg.toString());

        }
    }
}
